Random Numbers

This document shows you how to create a lot of random numbers.

The random module

Python Docs


In [4]:
import random # load the module

In [6]:
r = random.random() # equally distributed random number
print("Random 0 <= r == {} < 1".format(r))


Random 0 <= r == 0.13459591240598567 < 1

In [7]:
μ = 200
σ = 25

g = random.gauss(μ, σ)

print("Gauss distributed random number {} with μ={} and σ={}".format(g, μ, σ))


Gauss distributed random number 212.27657831120126 with μ=200 and σ=25

Plotting the numbers

Import numpy


In [8]:
import numpy as np
np.random.seed(0)

Generate random numbers.


In [49]:
normal_numbers = np.random.normal(μ, σ, size=100)
print("normal_numbers = {}".format(normal_numbers))


normal_numbers = [ 244.10130865  210.00393021  224.4684496   256.02232998  246.68894975
  175.568053    223.75221044  196.21606979  197.41952871  210.26496255
  203.60108928  236.35683767  219.02594313  203.04187541  211.09658082
  208.34185818  237.35197683  194.87104341  207.82669254  178.64760652
  136.1752546   216.34046489  221.61090497  181.44587449  256.7438656
  163.64085814  201.14396293  195.32040375  238.31948036  236.73396925
  203.87368564  209.45406299  177.80535631  150.48008829  191.30219627
  203.90872423  230.75726702  230.05949622  190.31682956  192.44243124
  173.78617587  164.49955157  157.34324523  248.76938488  187.25869546
  189.04814246  168.680116    219.4372589   159.65255381  194.68149299
  177.61333597  209.67256245  187.22987156  170.4841954   199.29544429
  210.70829676  201.66293056  207.56179744  184.14194766  190.93147085
  183.18848881  191.01117096  179.67134295  156.84293494  204.43565356
  189.95547659  159.24504133  211.56955639  177.31754089  201.29863489
  218.22726405  203.22457277  228.48501711  169.12935449  210.05854103
  182.87974773  178.23007127  185.52875838  192.2111867   201.40413356
  170.87125398  222.52066217  211.64156099  161.59390784  237.20630484
  247.3972294   229.46948928  195.5018791   173.23118446  226.36129317
  189.92057633  230.56112676  205.20687445  224.41597591  208.90915993
  217.6643292   200.26250052  244.64676235  203.17280232  210.04973409]

Install plotly from the command line:

We generate a plot


In [53]:
import numpy as np
import matplotlib.pyplot as plt

fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(8, 4))

ax0.hist(normal_numbers, 20, normed=1, histtype='stepfilled', facecolor='g', alpha=0.75)
ax0.set_title('stepfilled')

# Create a histogram by providing the bin edges (unequally spaced).
bins = [100, 150, 180, 195, 205, 220, 250, 300]
ax1.hist(normal_numbers, bins, normed=1, histtype='bar', rwidth=0.8)
ax1.set_title('unequal bins')

fig.tight_layout()
plt.show()



In [ ]: